<template>
  <el-popover
    v-if="importConfig.show"
    placement="bottom"
    trigger="hover"
  >
    <div class="popover-content">
      <el-button size="small" type="primary" style="margin-right:10px;" @click="downloadTemplate">模版下载</el-button>
      <el-upload
        ref="uploadExcelRef"
        class="upload-demo"
        accept=".xlsx,.xls"
        :before-upload="beforeUpload"
        :multiple="false"
        :auto-upload="true"
        list-type="text"
        :show-file-list="false"
        action=""
        :limit="1"
        :on-exceed="handleExceed"
        :http-request="httpRequest"
      >
        <el-button slot="trigger" size="small" type="success">上传文件</el-button>
      </el-upload>
    </div>

    <el-button slot="reference" size="small" type="primary" icon="el-icon-upload" style="margin: 0 10px;">导入</el-button>
  </el-popover>
</template>

<script>
export default {
  props: {
    importConfig: {
      type: Object,
      default() {
        return {}
      }
    }
  },

  methods: {
    async httpRequest(config) {
      try {
        const { api } = this.importConfig
        if (!api) throw new Error('请配置导入api')
        const file = config.file
        const formData = new FormData()
        formData.append('file', file)
        await api(formData)
        this.$message.success('数据导入成功')
      } catch (error) {
        this.$alert(error.msg, '错误', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          callback: action => {}
        })
        console.error('【上传失败】', error)
      } finally {
        this.$refs['uploadExcelRef'].clearFiles()
      }
    },

    async downloadTemplate() {
      try {
        const { downloadTemplateApi, templateUrl } = this.importConfig
        if (downloadTemplateApi) {
          await downloadTemplateApi()
        } else if (templateUrl) {
          this.toFile()
        } else {
          throw new Error('请配置模板下载api 函数或者资源url地址')
        }
      } catch (error) {
        console.error('【模板下载异常】', error)
      }
    },

    toFile() {
      try {
        const { templateUrl, templateName = '导入模板.xlsx' } = this.importConfig
        if (!templateUrl) throw new Error('请配置导入模板下载地址')
        const a = document.createElement('a')
        const event = new MouseEvent('click')
        a.download = templateName
        a.href = templateUrl
        a.dispatchEvent(event)
      } catch (error) {
        console.error('【模板下载失败】：', error)
      }
    },
    beforeUpload(file) {
      const isText = file.type === 'application/vnd.ms-excel'
      const isTextComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      return (isText || isTextComputer)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件`)
    }
  }
}
</script>

<style lang="scss" scoped>
.popover-content{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
